<template>
  <div class="charts_content">
    <div class="charts_border">
      <div id="seru_chart" class="chart_view"></div>
      <div id="question_chart" class="chart_view"></div>
      <div id="eat_chart" class="chart_view big_view"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'

import { getRecordToDay, queryAllFood, queryAllIngredientList, queryAllElementList, queryAllQuestionList } from './api.js'
import { getIngredientById } from '../settings/backend/api';


const toDayRecored = ref({})
const allFoodData = ref([])
const allIngredientData = ref([])
const elementMap = ref({})
const allElementData = ref([])
const allQuestionData = ref([])

onMounted(() => {
  getRecordDataToDay()
})

const getRecordDataToDay = () => {
  // 使用Promise.all减少延迟
  Promise.all([getRecordToDay(), queryAllFood(), queryAllIngredientList(), queryAllElementList()]).then(res => {
    toDayRecored.value = res[0].result
    allFoodData.value = res[1].result
    allIngredientData.value = res[2].result
    allElementData.value = res[3].result
    getElementMap() // 获取名称和id的字典
    initSeruChartToDay()
    initQuestionToDay()
    initEatOrDrinkToDat()
  })
}

const getElementMap = () => {
  const map = {}
  allElementData.value.forEach(item => {
    map[item.name] = item.id
  })
  elementMap.value = map
}

const initSeruChartToDay = () => {
  // 一天内摄入数据，蛋白质、碳水化合物、脂肪、膳食纤维、维生素C、维生素A、维生素B1、维生素B2
  let eatData = []
  const column = ['蛋白质', '碳水化合物', '脂肪', '膳食纤维', '维生素C', '维生素A', '维生素B1', '维生素B2']
  const food_list = []

  let { eat_list } = toDayRecored.value

  if (eat_list) {
    // 根据吃的食物计算摄入的营养物质
    eat_list = JSON.parse(eat_list) || {}

    console.log(eat_list, '===eat_list========>')
    // 早中晚餐合并
    const typeList = ['m', 'n', 'e']
    typeList.forEach(time => {
      if (eat_list[time]) {
        eat_list[time].forEach(item => {
          const { id, weight } = item
          if (!food_list.find(food => food.id === id)) {
            // 新的菜谱, weight需要转换为number类型
            food_list.push({
              id,
              weight: Number(weight)
            })
          } else {
            // 相同的菜谱重量相加
            const currentFood = eat_list[time].find(food => food.id === id)
            currentFood.weight += Number(weight)
            food_list.push(currentFood)
          }
        })
      }
    })

    console.log(food_list, '==food_list=========>')
    // 计算含量
    food_list.forEach(item => {
      const { id, weight } = item
      const food = allFoodData.value.find(food => food.id === id)
      if (food) {
        // 食谱的食材列表
        const ingredients = food.ingredients ? JSON.parse(food.ingredients) || [] : []
        ingredients.forEach(ingredient => {
          const { id: inId, weight: inWeight } = ingredient
          const ingredientData = allIngredientData.value.find(ing => ing.id === inId)
          // 食物的元素列表
          const nutrition_list = ingredientData.nutrition_list ? JSON.parse(ingredientData.nutrition_list) || [] : []
          console.log(nutrition_list, '=nutrition_list==========>')

          // 获取食材的元素列表
          const map = {}
          nutrition_list.forEach(ing => {
            map[ing.id] = ing
          })

          console.log(map, '=map==========>')

          // 待优化为code
          const protein = map[elementMap.value['蛋白质']]
          const fat = map[elementMap.value['碳水化合物']]
          const carb = map[elementMap.value['脂肪']]
          const fiber = map[elementMap.value['膳食纤维']]
          const vc = map[elementMap.value['维生素C']]
          // const va = map[elementMap.value['维生素A']]
          // const vb1 = map[elementMap.value['维生素B1']]
          // const vb2 = map[elementMap.value['维生素B2']]

          column.forEach

          console.log(carb, '==carb=========>')

          // 计算食材营养含量总和, 按照百分比计算
          const typeList = [protein, fat, carb, fiber, vc]
          typeList.forEach((ing, index) => {
            let value = 0
            if (ing) {
              const { weight } = ing
              value = weight * inWeight / 100
            }
            if (!eatData[index]) {
              eatData[index] = value
            } else {
              // 相加
              eatData[index] += value
            }
          })
        })
      }
    })
  } else {
    eatData = [0, 0, 0, 0, 0, 0, 0, 0]
  }

  console.log(eatData, '==最终数据=========>')

  const chart = echarts.init(document.getElementById('seru_chart'))
  chart.setOption({
    title: {
      text: '摄入营养',
      left: 'left',
      top: 20
    },
    tooltip: {},
    grid: {
      left: '20%',
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      data: ['蛋白质', '碳水化合物', '脂肪', '膳食纤维', '维生素C']
    },
    series: [
      {
        data: eatData,
        type: 'bar'
      }
    ]
  })
}

const initQuestionToDay = () => {
  // 答题统计 饼图
  const chart = echarts.init(document.getElementById('question_chart'))
  const question_number = toDayRecored.value.question_number || 0
  chart.setOption({
    title: {
      text: '答题统计',
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      top: '20%',
      left: '10%'
    },
    // color: ['#5470c6', '#e7e7e7'],
    series: [
      {
        name: '答题',
        type: 'pie',
        radius: '50%',
        label: {
          show: true,
          formatter: '{b}:{c}'
        },
        data: [
          { value: question_number, name: '答题' },
          { value: 10 - question_number, name: '未答题' }
        ]
      }
    ]
  })
}

const initEatOrDrinkToDat = () => {
  // 饮食，饮品 饼图
  const foods = toDayRecored.value.eat_list ? JSON.parse(toDayRecored.value.eat_list) || [] : []
  const foodListData = []
  const type = ['m', 'n', 'e']
  type.forEach(item => {
    const currentFoods = foods[item]
    if (currentFoods) {
      currentFoods.forEach(food => {
        if (food) {
          if (!foodListData.find(item => item.id === food.id)) {
            foodListData.push(food)
          } else {
            const lFood = foodListData.find(item => item.id === food.id)
            const lWeight = Number(lFood.weight)
            lFood.weight = lWeight + Number(food.weight)
          }
        }
      })
    }
  })
  const eatNameList = []
  foodListData.forEach(food => {
    const foodData = allFoodData.value.find(item => item.id === food.id)
    if (foodData) eatNameList.push({
      name: foodData.name,
      value: food.weight
    })
  })
  const drink = toDayRecored.value.jrink || 0
  const chart = echarts.init(document.getElementById('eat_chart'))
  chart.setOption({
    title: {
      text: '饮食记录',
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '10%'
    },
    top: '100',
    // color: ['#5470c6', '#e7e7e7'],
    series: [
      {
        name: '饮食',
        type: 'pie',
        radius: '50%',
        label: {
          show: true,
          formatter: '{b}:{c}g'
        },
        data: [
          ...eatNameList,
          { value: drink, name: '饮水' }
        ]
      }
    ]
  })
}

const initSeruChartByWeek = ({ eat_list }) => {
  // 一周内摄入数据，蛋白质、碳水化合物、脂肪、膳食纤维、维生素C、维生素A、维生素B1、维生素B2
  const chart = echarts.init(document.getElementById('seru_chart'))
  chart.setOption({
    title: {
      text: '摄入营养',
      left: 'left',
      top: 20
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['蛋白质', '碳水化合物', '脂肪', '膳食纤维', '维生素C', '维生素A', '维生素B1', '维生素B2'],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value'
    },
    series: []
  })
}


</script>

<style lang="scss" scoped>
.charts_content {
  width: 100%;
  // height: calc(100vh - 120px);
  // padding: 5px;
  // box-sizing: border-box;
  // ::v-deep .charts_border {
  //   border: 1px solid;
  //   box-sizing: border-box;
  // }
}
::v-deep .chart_view {
  width: 100%;
  height: 250px;
  margin-top: 10px;
}
::v-deep .big_view{
  width: 100%;
  height: 300px;
}
</style>
